//
//  WBNetworkTool.swift
//  weiboD
//
//  Created by gao2015 on 2016/12/3.
//  Copyright © 2016年 gao2015. All rights reserved.
//

import UIKit
import AFNetworking

enum requestType {
    //get 请求
    case get
    //post 请求
    case post
}

class WBNetworkTool: AFHTTPSessionManager {
    
//    typealias CallBack = (Any?, Error?)->()

    //提供一个单例供外界调用static修饰的变量外界的类可以直接调用
    static let shareTool : WBNetworkTool = {
        let tool = WBNetworkTool()
        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()
    
    //MARK:封装get/set方法
    func request(type:requestType, url:String, params:Any?, callBack: @escaping (Any?, Error?)->()) {
        //get请求
        if type == .get {
            get(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response,nil)
            }, failure: { (_, error) in
                callBack(nil,error)
            })
        }else{
        //post请求
            post(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response,nil)
                
            }, failure: { (_, error) in
                callBack(nil,error)
            })
        }
    }
}

//MARK:获取首页相关数据
extension WBNetworkTool{
    func requestHomeData(callBack : @escaping (Any?, Error?)->())  {
        //用户所关注的微博接口
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //入参
        let paramer = [
            "access_token" : WBUserAccoutViewModel.shareUserAccout.userAccount?.access_token!
        ]
        request(type: .get, url: url, params: paramer, callBack: callBack)
    }
    
}









//MARK:提供分类extension 用户获取第三方的请求数据的方法
extension WBNetworkTool{
    //获取access_token
    func requestAccessToken(code: String, callBack: @escaping (Any?, Error?)->()) {
        //参考接口文档
        let url = "https://api.weibo.com/oauth2/access_token"
        //请求参数
        let params = [
            "client_id": AppKey,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": Redirect_uri
        ]
        request(type: .post, url: url, params: params, callBack: callBack)
        
    }

    //获取用户信息
    func requestGetUserInfo(accessToken:String , uid:Int64, callBack: @escaping (Any?, Error?)->())  {
        let url = "https://api.weibo.com/2/users/show.json"
        //请求参数
            //access_token是从别的接口拿到的
        let params: [String:Any] = [
            "access_token" : accessToken,
            "uid" : uid
        ]
        request(type: .get, url: url, params: params, callBack: callBack)
    }
}
